<?php
class Core{
	const REQUEST_TYPE_NORMAL = 1;
	const REQUEST_TYPE_CRON = 2;

	private static $url = false;
	private static $req = false;
	private static $events = false;
	private $area = false;


	/**
	 * @var View
	 */
	private $view = false;
	
	function url()
	{
		return self::$url;
	}


	/**
	 * Enter description here...
	 *
	 * @return Events
	 */
	static function events()
	{
		return self::$events;
	}


	/**
	 * Enter description here...
	 * @return Request
	 */
	static function req()
	{
		return self::$req;
	}


	function __construct()
	{
		self::$url = new Url();
		_log("process ".self::$url->getUrl());
		self::$req = new Request(array_merge($_GET, $_POST), get_magic_quotes_gpc());
		self::$events = new Events();	

		//load modules functions
		foreach (glob(_cfg("path")."/_inc/mod/*", GLOB_ONLYDIR) as $entry)
			loadFunc("*.php", $entry."/func/");
	}


	function  prepare($area = "visitor", $type = Core::REQUEST_TYPE_NORMAL)
	{
        if (!in_array($type, array(self::REQUEST_TYPE_CRON))){
			session_start();
			_log("session started");
		}
		echo ob_get_clean();
		$this->area = $area;
	}


	function process()
	{
		$layout = "layout_".$this->area;
		if (!file_exists(_cfg("path")."/_inc/tpl/".$layout.".php"))
			$layout = "layout_default";

		$this->view = new View("tpl/".$layout);

		$alias = self::req()->get("alias");
		if (!$alias)
			$alias = "default";
		if (!file_exists(_cfg("path")."_inc/tpl/{$this->area}/{$alias}.php"))
			$alias = "tpl/default";
		else 
			$alias = "tpl/{$this->area}/$alias";

		$default = _cfg("{$this->area}.default");
	
		$mod = $this->req()->get("mod", $default['mod']);
		$act = $this->req()->getAction($default['act']);

		_fireEvent("PROCESS_START", $this->area, self::url());

		$view = new View($alias);
		$view->setVar("area", $this->area);
		$view->setVar("mod", $mod);
		$view->setVar("req", $this->req());
		$view->setVar("act", $act);

		$this->view->setVar("html", $view->fetch(),0);
        $postHTML = (_cfg('debug'))?_fireEvent("POST_RENDER_HTML"):array();
		$this->view->setVar("post_html", join('', $postHTML), 0);
		$this->view->setVar("mod",$mod);
		$this->view->setVar("act",$act);
        echo $this->view->fetch();
        exit;
	}
	
	function render()
	{
		self::$events->fireEvent("TEST_EVENT", "param1","param2", array(1,2));
		print_r($this->view->fetch());
	}
}
?>